package pers.jg.rrsserver.controller

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.google.gson.GsonBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import pers.jg.rrsserver.entity.ConsultA
import pers.jg.rrsserver.mapper.ConsultAMapper

@RestController
@CrossOrigin
class ConsultAController {

    val dateFormat = "yyyy-MM-dd'T'HH:mm:sssZ"

    class ConsultAList {
        lateinit var consultA: ArrayList<ConsultA>
    }

    @Autowired
    private lateinit var consultAMapper: ConsultAMapper

    @PostMapping("/api/postNewAnswer")
    fun postNewAnswer(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder()
            .setDateFormat(dateFormat)
            .create()
        val answer = gson.fromJson(data, ConsultA::class.java)
        println(answer.id)
        val res = consultAMapper.insert(answer)
        return res.toString()

    }

    @GetMapping("/api/getAnswerListByQid")
    fun getAnswerListByQid(
        @RequestParam(value = "qId", defaultValue = "") qId: String,
    ): String {
        val queryWrapper = QueryWrapper<ConsultA>()
        queryWrapper.eq("q_id", qId)
        queryWrapper.orderByDesc("date")   // 按照时间降序排序
        val list = consultAMapper.selectList(queryWrapper)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(list)
    }

    @PostMapping("/api/updateAnswer")
    fun updateAnswer(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder()
            .setDateFormat(dateFormat)
            .create()
        val answer = gson.fromJson(data, ConsultA::class.java)
        println(answer.id)
        val res = consultAMapper.updateById(answer)
        return res.toString()
    }

    @PostMapping("/api/deleteAnswer")
    fun deleteAnswer(
        @RequestParam("id") id: String
    ): String {
        println(id)
        return consultAMapper.deleteById(id).toString()
    }

    @GetMapping("/api/getAnswer")
    fun getAnswer(
        @RequestParam("id") id: String
    ): String {
        val answer = consultAMapper.selectById(id)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(answer)
    }

}